#!coding:utf-8
'''
Created on Aug 23, 2012

@author: join
'''
from lottery_terminal.common import utils, Constant
from lottery_terminal.models import Account, Period, Trade
from lottery_terminal.common.ticketutil import _ticket_obj,\
    ticket_model_ticket, pre_stop_dict, shengxiao_dict
import datetime
from lottery_terminal.service.lotteryservice.LoanLotteryService import LoanLottery
from lottery_terminal.service.lotteryservice.SSCLotteryService import SSCLottery
from lottery_terminal.rpc import rbc
from django.db import transaction
import json
import logging
from lottery_terminal.service.lotteryservice.ThreaDLotteryService import ThreaDLottery
from lottery_terminal.service.lotteryservice.SixAndOneLotteryService import SixAndOneLottery
from lottery_terminal.service.lotteryservice.FifteenFiveLotteryService import FifteenFiveLottery
from lottery_terminal.service.lotteryservice.SevenColorLotteryService import SevenColorLottery
from lottery_terminal.service.lotteryservice.baseService import BaseLottery

LOG = logging.getLogger('terminal')

@utils.ajaxrender
def chk_buy_lottery(req):
    '''购买彩票前先检查是否为开奖时间，是否店主额度账户充足'''
    lotterys = req.POST.getlist('lotterys[]')
    lotterycode = req.POST.get('type')
    mac = req.POST.get('mac')
    periodid = req.POST.get('periodid')
    periods = Period.objects.filter(lotterycode=lotterycode,periodid=periodid)
    period = periods[0]
    if period.awardtime<datetime.datetime.now():
        return u'期次过时，请返回主页面后重新选择购彩',400
    tradeamount = sum([int(t.split('#')[-1]) for t in lotterys])
    if tradeamount>20000:
        return u'购票失败,每次购买不能超过20000金额',400
    if not mac:
        return u'购票失败，机器无法识别',500
    tf_accounts = Account.objects.filter(deleted=False,accountType=2)
    if not tf_accounts:
        return u'尚未添加公司帐号',500
    if tf_accounts[0].balance<tradeamount:
        return u'彩票数量不足，请联系店主.',500
    
    accounts = Account.objects.filter(deleted=False,mac=mac)
    if not accounts:
        return u'购票失败，机器无法识别',400
    baseLottery = BaseLottery(lotterycode)
    currenttime = datetime.datetime.now()+datetime.timedelta(minutes=pre_stop_dict.get(lotterycode),seconds=2)
    is_buy_time = baseLottery.is_buytime(currenttime)[0]
    if not is_buy_time:
        return u'当前时间为开奖时间',400
#    account = accounts[0]
#    if account.balance<tradeamount:
#        return u'店主余额不足，无法购票',400
    
@utils.ajaxrender
def buy_lottery(req):
    '''购买彩票'''
    lotterys = req.POST.getlist('lotterys[]')
    lotterycode = req.POST.get('type')
    mac = req.POST.get('mac')
    buymethod = req.POST.get('buymethod') #购买方式，刷卡，投币或代购
    prizeType = req.POST.get('prizeType',0) #现金:0,银联：1
    periodid = req.POST.get('periodid')
    pricecard = req.POST.get('pricecard')
    card_password = req.POST.get('password')
    
    if lotterycode == Constant.SSQ_CODE: #彩票代码为双色球
        service = LoanLottery()
    elif lotterycode == Constant.SSC_CODE: #彩票代码为时时彩
        service = SSCLottery()
    elif lotterycode == Constant.THREE_D_CODE: #彩票代码为福彩3D
        service = ThreaDLottery()
    elif lotterycode == Constant.SIX_ONE_CODE: #彩票代码为东方6+1
        service = SixAndOneLottery()
    elif lotterycode == Constant.FIFTEEN_FIVE_CODE: #彩票代码为15选5
        service = FifteenFiveLottery()
    elif lotterycode == Constant.QLC_CODE: #彩票代码为七乐彩
        service = SevenColorLottery()
    
    if not pricecard and not card_password and buymethod=='2':
        return u'请刷额度卡并输入密码',400
    if not pricecard and buymethod=='2':
        return u'请刷额度卡',400
    if not card_password and buymethod=='2':
        return u'请输入密码',400
    
    
    accounts = Account.objects.filter(deleted=False,mac=mac)
    if not accounts:
        return u'购票失败，机器无法识别',400
    else:
        if buymethod=='2' and (accounts[0].account != pricecard or utils.getMD5Str(card_password) != accounts[0].password):
            return u'代购帐号不匹配，请重试',400
        
    tradeamount = sum([int(t.split('#')[-1]) for t in lotterys])
    if buymethod != '0':
        account = accounts[0]
        if account.balance<tradeamount:
            return u'店主余额不足，无法购票',400
    if tradeamount>20000:
        return u'购票失败,每次购买不能超过20000金额',400
    if not mac:
        return u'购票失败，机器无法识别',500

#    if len(lotterys)>5:
#        return u'购票失败,每次不能超过5注',400
    periods = Period.objects.filter(lotterycode=lotterycode,periodid=periodid)
    period = periods[0]
    
    tf_accounts = Account.objects.filter(deleted=False,accountType=2)
    if not tf_accounts:
        return u'尚未添加公司帐号',500
    tianfu_account = tf_accounts[0]
    
#    ticketutil = TicketUtil(lotterycode)
    currenttime = datetime.datetime.now()+datetime.timedelta(minutes=pre_stop_dict.get(lotterycode),seconds=2)
    is_buy_time = service.is_buytime(currenttime)[0]  #TODO:计算是否为可以购买彩票时间有待考证
    
    if not is_buy_time:
        return u'当前时间为开奖时间',400
    ticket_infos = {'period':period,'codes':lotterys,'buymethod':buymethod,'tradeAmount':tradeamount,
                        'account':accounts[0],'tianfu_account':tianfu_account,'prizeType':prizeType}
    
    try:
        result = service.buy_ticket(ticket_infos)  #result格式目前是 msg,200
    except Exception as e:
        LOG.exception('an exception occured:%s' % e)
        result = u'未知错误，购买彩票失败',500
    return result

@utils.render
def zhongjiang(req,batchid):
    '''查询中奖'''
    result = {}
    if len(batchid.split('|')) == 3:
        batchid,mac = batchid.split('|')[:2]
        #print 'batchid is:',batchid
        LOG.info("batchid is:%s"%batchid)
        batchid = '%s'%(int(batchid)-123) #解密
    else:
        batchid,mac = batchid.split('|')
        
    #print 'batchid is:',batchid
    LOG.info("batchid is:%s"%batchid)
    result['batchid'] = batchid
    result['mac'] = mac
    if not batchid:
        result['errormsg'] = u'彩票不存在'
        return 'zhongjiang/weizhongjiang.html',result
    trade = Trade.objects.filter(batchid=batchid)
    if not trade:
        result['errormsg'] = u'彩票不存在'
        return 'zhongjiang/weizhongjiang.html',result
    trade = trade[0]
    mac_account=Account.objects.filter(deleted=0,mac=mac)
    if not mac_account:
        result['errormsg'] = u'机器不识别'
        return 'zhongjiang/weizhongjiang.html',result
    
#        trade.prizeaccount=mac_account[0]
#        trade.save()
    period = trade.period
    result['periodid'] = period.periodid
    lotterycode = '01'
    if trade.tradeTicketType == 0:
        lotterycode = '20'
        result['lotteryname'] = u'时时彩'
    elif trade.tradeTicketType == 1:
        lotterycode = '01'
        result['lotteryname'] = u'双色球'
    elif trade.tradeTicketType == 2:
        lotterycode = '07'
        result['lotteryname'] = u'七乐彩'
    elif trade.tradeTicketType == 3:
        lotterycode = '05'
        result['lotteryname'] = u'福彩3D'
    elif trade.tradeTicketType == 4:
        lotterycode = '15'
        result['lotteryname'] = u'十五选五'
    elif trade.tradeTicketType == 5:
        lotterycode = '06'
        result['lotteryname'] = u'东方6+1'
    
    awardcodes = period.awardcodes
    baselottery = BaseLottery(lotterycode)

    if not awardcodes:
        awardcodes = baselottery.query_award_code(period.periodid)
    if period.awardtime>=datetime.datetime.now():
        result['errormsg']=u'尚未开奖'
        return 'zhongjiang/weizhongjiang.html',result
    
    awardcodes_info = {}
    if awardcodes:
        if lotterycode == '01' or lotterycode == '07':
            awardcodes_info['reds'] = awardcodes.split('|')[0].split(',')
            awardcodes_info['blue'] = awardcodes.split('|')[1]
        elif lotterycode == '20' or lotterycode == '05' or lotterycode == '15':
            awardcodes_info['reds'] = awardcodes.split(',')
        elif lotterycode == '06':
            awardcodes_info['reds'] = awardcodes.split('|')[0].split(',')
            awardcodes_info['blue'] = shengxiao_dict.get(awardcodes.split('|')[1])
        result['awardcodes'] = awardcodes_info
    _ticket_obj = ticket_model_ticket.get(trade.tradeTicketType)
    tickets = _ticket_obj.objects.filter(tradeId=trade,deleted=False,status=4)
    if tickets:
        result['prizetime'] = utils.convert_datetime_to_str(tickets[0].prizetime, '%Y-%m-%d %H:%M:%S')
#            result['prizeplace'] = trade.accountid.loginname
        result['prizeplace'] = mac_account[0].address
        result['awardmoney'] = sum([t.prizemoney if t.prizemoney else 0 for t in tickets])
        return 'zhongjiang/yizhongjiang.html',result
    
    if period.status == 0: #尚没有查询过中奖名单列表,进行名单列表的查询
        result['errormsg'] = u'中奖统计中，请稍后'
        return 'zhongjiang/weizhongjiang.html',result
    tickets = _ticket_obj.objects.filter(tradeId=trade,deleted=False) #购买成功的彩票，且未兑奖
        
    award_money = 0
    hasbigprize = ""
    for ticket in tickets: #叠加所有彩票的中奖金额
        if ticket.validitytime<utils.now():
            result['errormsg'] = u'您的彩票已过期'
            return 'zhongjiang/weizhongjiang.html',result
        award_money += ticket.prizemoney if ticket.prizemoney else 0
        if ticket.hasbigprize == '1': #ticket.prizemoney>10000: #
            hasbigprize = "1"
    result['awardmoney'] = award_money
    result['hasbigprize'] = hasbigprize
    result['phone'] = rbc.telephone
#   _ticket_obj = ticket_model_ticket.get(trade.tradeTicketType)

    if award_money>0:
        href = 'zhongjiang'
    else:
        href = 'weizhongjiang'
    return 'zhongjiang/%s.html'% href,result
    
    
@utils.ajaxrender
@transaction.commit_on_success
def prize_confirm(req):
    '''返奖确认,增加店主的额度账户，修改彩票状态为已兑奖'''
    batchid = req.POST.get('batchid')
    acc = req.POST.get('acc_num')
    account111 = Account.objects.filter(account=acc,deleted=False).all()
    trades = Trade.objects.filter(batchid=batchid,deleted=False)
    trade = trades[0] if trades else None
    if not trade:
        return u'返奖确认失败，请联系管理员',500
    _model = ticket_model_ticket.get(trade.tradeTicketType)
    tickets = _model.objects.filter(deleted=False,tradeId=trade)
    if tickets[0].status == 4:
        return u'已兑奖，不能重复兑奖',400
    tickets.update(status=4,prizetime=datetime.datetime.now())
    account111=account111[0] if account111 else None
    account111.balance += sum([t.prizemoney if t.prizemoney else 0 for t in tickets])
    account111.save()
    
    prizemoney = sum([t.prizemoney if t.prizemoney else 0 for t in tickets])
    LOG.exception("prize_confirm:add balance to account:%s,prizemoney:%s,new balance:%s"%(account111.account,prizemoney,account111.balance))
    LOG.exception("batchid:%s,account:%s"%(batchid,acc))
    
    trade.prizeaccount=account111
    trade.save()
    return json.dumps({'msg':'ok'}),200

@utils.ajaxrender
def trade_pos_fail(req):
    '''因为pos机的故障导致交易失败情况的处理'''
    sd_batchid = req.POST.get('sd_batchid')
    trades = Trade.objects.filter(desc=sd_batchid)
    if trades:
        trade = trades[0]
        trade.status=4
        trade.save()
    else:
        return json.dumps({'msg':u'店主额度补偿失败'}),500
    return json.dumps({'msg':'ok'}),200
